封面圖是台灣好行的網站,有個可互動的台灣img
今日的目標是做一個台灣地圖上的區域 hover 時要顯示該區域
的 MVP
借台灣好行的圖片來用~
以前第一次看到在一張圖片上點不同位置可以做不同事情很驚訝!
這個我們叫做 Image Maps (影像地圖)
對一張圖片上的特定區域做上標記
,就能觸發對應事件
<img usemap="#myMap" src="img.png" />
<map name="myMap">
<area shape="rect" coords="0,0,82,126" href="" alt="" />
<area shape="circle" coords="90,58,3" href="" alt="" />
</map>
img
標籤要設定usemap
="#字號開頭加上 name"map
和area
name
area 的重要屬性
附上w3c 文件
這邊介紹一個工具是可以上傳圖片,直接在網頁上標記座標
最後幫你產生程式碼,超方便!
上圖可以清楚呈現不同shape的效果
若shape空白預設是rect
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Taiwan Map</title>
<style>
p {
font-size: 3rem;
}
.map-wrapper {
display: flex;
}
</style>
</head>
<body>
<div class="map-wrapper">
<img
src="https://www.taiwantrip.com.tw//Areas/Frontend/Content/img/mapen/map-e01.png"
usemap="#image-map"
class="img-fluid"
id="Image-Maps"
alt="台灣地圖"
/>
<p id="areaName">.</p>
</div>
<map name="image-map">
<area
shape="poly"
coords="547,123,560,133,571,141,567,129,575,122,572,102,561,84,550,88,538,98,546,106"
target=""
alt="臺北市"
title="臺北市"
data-lang-tag="臺北市"
/>
<area
shape="poly"
coords="594,90,587,78,578,78,564,56,557,56,527,77,518,90,501,102,518,119,515,134,542,128,542,111,533,97,561,76,571,94,577,116,583,124,571,134,575,139,572,145,551,133,546,129,511,140,499,146,515,173,527,172,540,204,567,196,569,180,613,150,622,149,639,134,653,129,668,130,654,117,640,102,625,98,624,105,610,108,620,118,614,123,593,119,580,102,589,98"
href="javascript: void(0);"
target=""
alt="新北市"
title="新北市"
data-lang-tag="新北市"
/>
<!-- ...etc -->
</map>
<script>
document.querySelectorAll("area").forEach((area) => {
area.addEventListener("mouseover", (e) => {
e.preventDefault();
const tagName = this.getAttribute("data-lang-tag");
handleHover(tagName);
});
});
function handleHover(locationName) {
areaName.textContent = locationName || "";
}
</script>
</body>
</html>